import apiClient from "@/lib/interceptor";

// API 响应接口
export interface ApiResponse<T> {
	code: number;
	data: T;
	message: string;
	msg?: string;  // 添加可选的 msg 字段
}

// 定义部门类型
export interface Department {
	numbering: string;
	name: string;  // 添加 name 字段
	positions: Position[];
}

// 定义岗位类型
export interface Position {
	positionName: string;
	positionNumber: string;  // 岗位编号
	positionProperties?: string | null;
	jobDescription: string;
	jobRequired: string;
	person: number;
	professionalSkillsRight: number;  // 添加专业技能权重
	communicationSkillsRight: number;  // 添加沟通能力权重
	teamworkAbilityRight: number;  // 添加团队协作权重
}

// 定义招聘计划请求参数类型
export interface RecruitmentPlan {
	planName: string;
	planCode: string;
	planType: number;
	depts?: Department[] | null;
	recruiterId?: string | null;
	recruiterName?: string | null;
	recruiterPhone?: string | null;
	recruitmentConditions?: string | null;
	benefitsDescription?: string | null;
	startDate: string;
	endDate: string;
	publishDate: string;
	interviewProcess?: string | null;
	approveStatus: number;
	approverId: string;
	notes?: string | null;
	content?: string | null;
	[key: string]: any;
}

// 定义修改招聘公告请求参数类型
export interface UpdateRecruitmentAnnouncementParams {
	planId: number;
	numbering?: string;                         // 用人部门（二级学院）编号（planType不为3时必填）
	positionName?: string;                        // 招聘岗位名称（planType不为3时必填）
	jobDescription?: string | null;               // 修改后的岗位描述
	jobRequired?: string | null;                  // 修改后的任职要求
	person?: string | null;                       // 修改后的招聘人数
	content?: string | null;                      // 修改后的公告内容（planType为3时必填）
	professionalSkillsRight?: number | null;      // 修改后的专业技能的权
	communicationSkillsRight?: number | null;     // 修改后的沟通能力的权
	teamworkAbilityRight?: number | null;         // 修改后的团队协作的权
}

// RecruitmentAnnouncement 接口用于描述后端返回的招聘公告数据结构，
// 方便前端进行类型检查、数据处理和展示招聘公告详情。
export interface RecruitmentAnnouncement {
	planId: number;
	planName: string;
	planCode: string;
	planType: number;
	depts: Department[] | null;
	positions?: Position[];
	recruiterId: string | null;
	recruiterName: string | null;
	recruiterPhone: string | null;
	recruitmentConditions: string | null;
	benefitsDescription: string | null;
	startDate: string;
	endDate: string;
	publishDate: string;
	interviewProcess: string | null;
	approveStatus: number;
	approverId: string;
	notes: string | null;
	attachments: string;
	createdBy: string | null;    // 使用驼峰命名
	updatedBy: string | null;    // 使用驼峰命名
	createdAt: string | null;    // 使用驼峰命名
	updatedAt: string | null;    // 使用驼峰命名
	content: string | null;
}

// 定义后端返回的数据结构接口
interface BackendAnnouncement {
	planId: number;
	planName: string;
	planCode: string;
	planType: number;
	depts: Department[] | null;
	positions?: Position[];
	recruiterId: string | null;
	recruiterName: string | null;
	recruiterPhone: string | null;
	recruitmentConditions: string | null;
	benefitsDescription: string | null;
	startDate: string;
	endDate: string;
	publishDate: string;
	interviewProcess: string | null;
	approveStatus: number;
	approverId: string;
	notes: string | null;
	attachments: string;
	created_by: string | null;  // 后端返回的字段名
	updated_by: string | null;  // 后端返回的字段名
	created_at: string | null;  // 后端返回的字段名
	updated_at: string | null;  // 后端返回的字段名
	content: string | null;
}

// 新增招聘公告
export const createRecruitmentPlan = async (planData: RecruitmentPlan) => {
	try {
		// 数据预处理
		const processedData: RecruitmentPlan = {
			planName: planData.planName,
			planCode: planData.planCode,
			planType: Number(planData.planType),
			// 日期格式转换为 ISO 格式
			startDate: new Date(planData.startDate).toISOString(),
			endDate: new Date(planData.endDate).toISOString(),
			publishDate: new Date(planData.publishDate).toISOString(),
			// 固定为发布未审批状态，approveStatus 设为 0
			approveStatus: 0,
			approverId: planData.approverId,
			// 处理部门和岗位数据，仅当计划类型不为 3 时传递
			depts:
				planData.planType !== 3
					? planData.depts?.map((dept) => ({
							numbering: dept.numbering,  // 使用 numbering 而不是 deptSelect
							name: dept.name || '',  // 添加 name 字段
							positions: dept.positions.map((pos) => ({
								positionName: pos.positionName,
								positionNumber: pos.positionNumber,
								positionProperties: planData.planType === 1 ? pos.positionProperties : null,
								jobDescription: pos.jobDescription,
								jobRequired: pos.jobRequired,
								person: Number(pos.person),
								professionalSkillsRight: Number(pos.professionalSkillsRight || 0),
								communicationSkillsRight: Number(pos.communicationSkillsRight || 0),
								teamworkAbilityRight: Number(pos.teamworkAbilityRight || 0),
							}))
					  }))
					: null,
			// 根据计划类型处理可选字段
			// 当 planType 为 3 时，设置所有相关字段为空字符串
			recruiterId: planData.planType === 3 ? "" : planData.recruiterId,
			recruiterName: planData.planType === 3 ? "" : planData.recruiterName,
			recruiterPhone: planData.planType === 3 ? "" : planData.recruiterPhone,
			recruitmentConditions: planData.planType === 3 ? "" : planData.recruitmentConditions,
			benefitsDescription: planData.planType === 3 ? "" : planData.benefitsDescription,
			interviewProcess: planData.planType === 3 ? "" : planData.interviewProcess,
			// 公告内容只有第三种招聘类型时提交
			content: planData.planType === 3 ? planData.content : null,
			notes: planData.notes || null
		};

		// 验证专任教师（planType === 2）的相关字段
		if (processedData.planType === 2) {
			if (!processedData.depts?.length) {
				throw new Error("专任教师必须添加至少一个部门");
			}
			for (const dept of processedData.depts) {
				if (!dept.positions?.length) {
					throw new Error(`部门 ${dept.numbering} 必须添加至少一个岗位`);
				}
			}
		}

		// 验证其他岗位（planType === 3）的相关字段
		if (processedData.planType === 3) {
			if (!processedData.content) {
				throw new Error("其他岗位必须填写公告内容");
			}
		}

		console.log("发送请求到后端，数据:", JSON.stringify(processedData, null, 2));
		const response = await apiClient.post<ApiResponse<any>>("/recruit/announcements", processedData);
		console.log("后端响应:", JSON.stringify(response, null, 2));

		if (response?.data?.code === 1) {
			return response;
		} else {
			const errorMsg = response?.data?.msg || response?.data?.message;
			console.error("业务错误:", {
				code: response?.data?.code,
				message: errorMsg,
				data: response?.data
			});
			throw new Error(errorMsg || "创建失败，服务器返回异常响应");
		}
	} catch (error: any) {
		console.error("创建招聘计划失败:", error);
		if (error.response) {
			throw new Error(error.response.data?.message || error.response.data?.msg || "服务器返回错误");
		} else if (error.request) {
			throw new Error("服务器未响应");
		} else {
			throw error;
		}
	}
};

// 获取所有招聘公告
export const getRecruitmentAnnouncements = async () => {
  try {
    console.log('开始获取招聘公告');
    const response = await apiClient.get('/recruit/announcements/get');
    console.log('API 原始响应:', response); // 添加日志
    
    // 确保响应数据格式正确
    if (response && typeof response === 'object' && 'data' in response) {
      // 检查 recruiterId 字段
      if (response.data && response.data.data && Array.isArray(response.data.data)) {
        console.log('招聘公告数量:', response.data.data.length);
        response.data.data.forEach((item: any, index: number) => {
          console.log(`第 ${index + 1} 条招聘公告:`, {
            planId: item.planId,
            planName: item.planName,
            recruiterId: item.recruiterId,
            recruiterName: item.recruiterName
          });
        });
      }
      return response.data;
    } else {
      console.error('API 响应格式错误:', response);
      throw new Error('API 响应格式错误');
    }
  } catch (error) {
    console.error('API 调用错误:', error);
    throw error;
  }
};

// 修改招聘公告(用人部门的岗位)
export const updateRecruitmentAnnouncement = async (
	updateData: UpdateRecruitmentAnnouncementParams
) => {
	try {
		// 输出请求数据日志
		console.log("发送修改请求到后端，数据:", JSON.stringify(updateData, null, 2));
		const response = await apiClient.patch<ApiResponse<any>>(
			"/recruit/announcements",
			updateData
		);
		console.log("后端响应:", JSON.stringify(response, null, 2));

		if (response?.data?.code === 1) {
			return response;
		} else {
			const errorMsg = response?.data?.msg || response?.data?.message;
			console.error("业务错误:", {
				code: response?.data?.code,
				message: errorMsg,
				data: response?.data
			});
			throw new Error(errorMsg || "修改失败，服务器返回异常响应");
		}
	} catch (error: any) {
		console.error("修改招聘公告失败:", error);
		if (error.response) {
			throw new Error(
				error.response.data?.message ||
					error.response.data?.data||
					error.response.data?.msg ||
					"服务器返回错误"
			);
		} else if (error.request) {
			throw new Error("服务器未响应");
		} else {
			throw error;
		}
	}
};

// 删除招聘公告
export const deleteRecruitmentAnnouncement = async (planId: number) => {
	try {
	  const response = await apiClient.delete<ApiResponse<any>>(`/recruit/announcements?planId=${planId}`);
  
	  if (response.data.code === 1) {
		return response.data;
	  } else {
		const errorMsg = response.data.msg || "删除失败";
		console.error("删除招聘公告失败:", {
		  message: errorMsg,
		  data: response?.data
		});
		throw new Error(errorMsg);
	  }
	} catch (error: any) {
	  console.error("删除招聘公告失败:", error);
	  if (error.response) {
		throw new Error(error.response.data?.message || error.response.data?.msg || "服务器返回错误");
	  } else if (error.request) {
		throw new Error("服务器未响应");
	  } else {
		throw error;
	  }
	}
  };

// 审批状态枚举
export const ApproveStatus = {
  PENDING_PUBLISH: 0, // 发布未审批
  PENDING_MODIFY: 1,  // 修改未审批
  APPROVED: 2,        // 已通过
  REJECTED: 3,        // 已拒绝
} as const;

// 计划类型枚举
export const PlanType = {
  MANAGEMENT: 1,      // 管理岗位
  TEACHER: 2,         // 专任教师
  OTHER: 3,           // 其他岗位
} as const;

//招聘计划岗位
export interface AnnouncementPosition {
	positionNumber: string;
	positionName: string;
	// 岗位性质仅在管理岗位招聘时传递，其他情况可以为 null
	positionProperties?: string | null;
	jobDescription: string;
	jobRequired: string;
	person: number;
	professionalSkillsRight: number;
	communicationSkillsRight: number;
	teamworkAbilityRight: number;
}

//招聘计划用人部门
export interface HiringDept {
	// 用人部门（二级学院）的编号
	numbering: string;
	// 该部门下的所有招聘岗位
	positions: AnnouncementPosition[];
}

//新建用人部门岗位DTO
export interface CreateDeptPositionsRequest {
	// 岗位类型（管理岗位招聘时为 1，其它类型不调用该接口）
	planType: number;
	// 招聘计划的主键 id
	planId: number;
	// 用人部门列表，每个部门都包含其对应的岗位信息
	depts: HiringDept[];
}

//新建用人部门和岗位的请求
export const createDeptPositions = async (params: CreateDeptPositionsRequest) => {
	try {
		const response = await apiClient.post<ApiResponse<any>>(
			'/recruit/announcements/positions',
			params
		);
		console.log("创建用人部门岗位响应:", response.data);
		if (response.data && response.data.code === 1) {
			return response.data;
		} else {
			const errorMsg = response.data?.data || response.data?.msg || response.data?.message || "新增用人部门岗位失败";
			console.error("业务错误:", errorMsg);
			throw new Error(errorMsg);
		}
	} catch (error: any) {
		console.error("创建用人部门岗位失败:", error);
		if (error.response) {
			throw new Error(
				error.response.data?.message ||
				error.response.data?.msg ||
				"服务器返回错误"
			);
		} else if (error.request) {
			throw new Error("服务器未响应");
		} else {
			throw error;
		}
	}
};

//要删除的用人部门的岗位
export interface DeleteDeptPosition {
	planId: number;           // 招聘计划的主键id
	numbering: string;        // 用人部门（二级学院）的编号
	positionName: string;     // 招聘岗位名称
}

//删除用人部门的岗位的集合
export interface DeleteDeptPositionsRequest {
	delPositions: DeleteDeptPosition[];  // 要删除的岗位列表
}

//删除用人部门的岗位的请求
export const deleteDeptPositions = async (params: DeleteDeptPositionsRequest) => {
	try {
		const response = await apiClient.delete<ApiResponse<any>>(
			'/recruit/announcements/positions',
			{
				// axios DELETE 请求传递请求体需要配置 data 属性
				data: params
			}
		);
		console.log("删除用人部门岗位响应:", response);
		if (response.data && response.data.code === 1) {
			return response.data;
		} else {
			const errorMsg = response.data?.msg || response.data?.message || "删除用人部门岗位失败";
			console.error("业务错误:", errorMsg);
			throw new Error(errorMsg);
		}
	} catch (error: any) {
		console.error("删除用人部门岗位请求失败:", error);
		if (error.response) {
			throw new Error(
				error.response.data?.message ||
				error.response.data?.msg ||
				"服务器返回错误"
			);
		} else if (error.request) {
			throw new Error("服务器未响应");
		} else {
			throw error;
		}
	}
};

// 定义分页查询参数接口
export interface GetRecruitmentAnnouncementsParams {
    page?: number;          // 当前页码
    pageSize?: number;      // 每页数据条数
    planType?: number;      // 计划类型：1-管理岗位，2-专任教师，3-其他岗位
}

// 定义分页响应数据接口
export interface PaginatedResponse<T> {
    records: T[];           // 当前页的数据记录
    total: number;          // 总记录数
    size: number;          // 每页显示条数
    current: number;       // 当前页码
    pages: number;         // 总页数
}

/**
 * 获取招聘计划（分页版本）
 * @param params 分页查询参数
 * @returns 分页后的招聘计划数据
 */
export const getRecruitmentAnnouncementsPaginated = async (params?: GetRecruitmentAnnouncementsParams) => {
    try {
        // 构建查询参数
        const queryParams = new URLSearchParams();
        
        // 使用默认值，确保 page 和 pageSize 总是有值
        const page = params?.page ?? 1;
        const pageSize = params?.pageSize ?? 10;
        
        // 添加基础分页参数
        queryParams.append('page', page.toString());
        queryParams.append('pageSize', pageSize.toString());
        
        // 只有当 planType 是数字时才添加
        if (typeof params?.planType === 'number') {
            queryParams.append('planType', params.planType.toString());
        }

        const queryString = queryParams.toString();
        const url = `/approval/recruit/announcements/get${queryString ? `?${queryString}` : ''}`;
        
        console.log('请求 URL:', url);
        console.log('请求参数:', { page, pageSize, planType: params?.planType });

        const response = await apiClient.get<ApiResponse<{
            row: RecruitmentAnnouncement[];
            total: number;
        }>>(url);

        console.log('原始 API 响应:', response);

        if (!response.data) {
            throw new Error('服务器返回空响应');
        }

        if (response.data.code !== 1) {
            throw new Error(response.data.message || '获取招聘计划列表失败');
        }

        // 直接使用后端返回的数据，不做字段映射
        return {
            records: response.data.data.row || [],
            total: response.data.data.total || 0,
            size: pageSize,
            current: page,
            pages: Math.ceil((response.data.data.total || 0) / pageSize)
        };
    } catch (error: any) {
        console.error('获取招聘计划列表失败:', error);
        if (error.response) {
            const errorMsg = error.response.data?.message || 
                           error.response.data?.msg || 
                           '服务器返回错误';
            throw new Error(errorMsg);
        } else if (error.request) {
            throw new Error('服务器未响应');
        } else {
            throw error;
        }
    }
};

// // 获取公开的招聘公告
// export const getPublicAnnouncements = () => {
//   return apiClient.get('/recruitment/announcements/public', {
//     headers: {
//       'Content-Type': 'application/json'
//     }
//   });
// };